package com.luoqiz.file.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.luoqiz.common.httpEntity.HttpResponseBase;
import com.luoqiz.common.httpEntity.HttpResponseService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "文件測試")
@RestController
@RequestMapping("/file")
public class FileUploadController {

	@Value(value = "${filePath:D:\\data\\test/}")
	private String filePath;

	@ApiOperation(value = "多文件上传、文件字段名为file")
	@PostMapping("/upload/mutil")
	public HttpResponseBase uploadFile(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		MultipartFile file = null;
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			// 文件名
			String fileName = file.getOriginalFilename();

			// 文件后缀
			String suffixName = fileName.substring(fileName.lastIndexOf("."));

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-S");
			// 重新生成唯一文件名，用于存储数据库
			String newFileName = simpleDateFormat.format(new Date()) + "-" + RandomUtils.nextInt(1000, 100000)
					+ suffixName;
			// System.out.println("新的文件名： " + newFileName);

			// 创建文件
			String filePathAndName = file.getContentType().substring(0, file.getContentType().indexOf("/"));
			File dest = new File(filePath + filePathAndName);
			map.put(fileName, "/upload/" + filePathAndName + "/" + newFileName);
			if (!dest.exists()) {
				dest.mkdirs();
			}
			try {
				file.transferTo(new File(dest.getPath() + "/" + newFileName));
			} catch (IllegalStateException | IOException e) {
				log.error("错误");
				e.printStackTrace();
			}

		}
		file = null;

		return HttpResponseService.setSuccess(map);

	}

	@ApiOperation(value = "多文件上传、文件字段名为file")
	@PostMapping("/upload/mutil2")
	public List<Map<String, String>> upload2(@RequestParam("file") MultipartFile[] files) throws IOException {
		if (files == null || files.length == 0) {
			return null;
		}
		List<Map<String, String>> results = new ArrayList<>();
		for (MultipartFile file : files) {
			// TODO Spring Mvc 提供的写入方式
			file.transferTo(new File(filePath + file.getOriginalFilename()));
			Map<String, String> map = new HashMap<>(16);
			map.put("contentType", file.getContentType());
			map.put("fileName", file.getOriginalFilename());
			map.put("fileSize", file.getSize() + "");
			results.add(map);
		}
		return results;
	}

	@ApiOperation(value = "单文件上传文件,文件字段名为file")
	@PostMapping("/upload/single")
	public HttpResponseBase uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		// 文件名
		String fileName = file.getOriginalFilename();
		// 文件后缀
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-S");
		// 重新生成唯一文件名，用于存储数据库
		String newFileName = simpleDateFormat.format(new Date()) + "-" + RandomUtils.nextInt(1000, 100000) + suffixName;
		System.out.println("新的文件名： " + newFileName);
		// 创建文件
		String filePathAndName = file.getContentType().substring(0, file.getContentType().indexOf("/"));
		File dest = new File(filePath + filePathAndName);
		if (!dest.exists()) {
			dest.mkdirs();
		}
		try {
			file.transferTo(new File(dest.getPath() + "/" + newFileName));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}

		return HttpResponseService.setSuccess("/upload/" + filePathAndName + "/" + newFileName);
	}

	@ApiOperation(value = "删除文件，格式      /deleteFile?filePath=....")
	@GetMapping("/deleteFile")
	public HttpResponseBase deleteFile(String filePath) {
		if (filePath.startsWith("/upload")) {
			filePath = filePath.substring(7);

		}
		File file = new File(filePath + "/" + filePath);
		boolean flag = false;
		if (file.exists()) {
			flag = file.delete();
		} else {
			return HttpResponseService.setError("此文件不存在", false);
		}
		if (flag) {
			return HttpResponseService.setSuccess(true);
		}
		return HttpResponseService.setError("", false);
	}
	
    @GetMapping("/down")
    public void downloadFileAction(HttpServletRequest request, HttpServletResponse response) {
 
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            File file = new File("d:/test13.pdf");
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
            IOUtils.copy(fis,response.getOutputStream());
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    public void downProcessFile(HttpServletRequest request,HttpServletResponse response,String path){
    	    try {
    	      File file = new File(path);
    	      String filename = file.getName();// 获取日志文件名称
    	      InputStream fis = new BufferedInputStream(new FileInputStream(path));
    	      byte[] buffer = new byte[fis.available()];
    	      fis.read(buffer);
    	      fis.close();
    	      response.reset();
    	      // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
    	      response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
    	      response.addHeader("Content-Length", "" + file.length());
    	      OutputStream os = new BufferedOutputStream(response.getOutputStream());
    	      response.setContentType("application/octet-stream");
    	      os.write(buffer);// 输出文件
    	      os.flush();
    	      os.close();
    	    } catch (Exception e) {
    	    }
    	  }
}